<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\SchoolStoreRequest;
use App\Models\Qh_School;
use App\Models\Qh_SchoolPlan;
use App\Models\Qh_SchoolSpec;
use Carbon\Carbon;
use DB;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Storage;
use Throwable;
use function PHPUnit\Framework\isFalse;

class SchoolController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = Qh_School::filter(\request()->all())->orderByDesc('id')->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param SchoolStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(SchoolStoreRequest $request)
    {
        $params = $request->validated();
        if (!empty($params['images'])) $params['images'] = implode(',', $params['images']);
        if (!empty($params['spec'])) {
            $specIds = $params['spec'];
        }
        unset($params['spec']);

        if (!empty($params['province'])) {
            $params['province'] = json_encode($params['province'], JSON_UNESCAPED_UNICODE);
        }

        $school = Qh_School::create($params);
        if (isset($specIds)) {
            $school->spec()->sync($specIds);
        }

        return $this->restful($school);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param SchoolStoreRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(SchoolStoreRequest $request, int $id)
    {
        $params = $request->validated();
        if (!empty($params['images'])) $params['images'] = implode(',', $params['images']);
        if (!empty($params['spec'])) {
            $specIds = $params['spec'];
        }
        unset($params['spec']);

        if (!empty($params['province'])) {
            $params['province'] = json_encode($params['province'], JSON_UNESCAPED_UNICODE);
        }

        $school = Qh_School::findOrFail($id);
        $result = $school->update($params);
        if (isset($specIds)) {
            $school->spec()->sync($specIds);
        }
        return $this->restful($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $result = Qh_School::where('id', $id)->delete();

        return $this->restful($result);
    }

    /**
     * 学校导入
     * @return JsonResponse|object
     * @throws Exception
     * @throws Throwable
     */
    public function import() {
        $params = request()->validate([
            'jsonPath' => 'bail|required|string',
            'pathType' => 'bail|nullable|in:1,2'
        ], request()->all());

        if (empty($params['pathType'])) $params['pathType'] = 1;
        if ($params['pathType'] == 2) {
            $filePath = $params['jsonPath'];
        } else {
            $filePath = storage_path($params['jsonPath']);
        }

        if (!file_exists($filePath)) {
            throw new Exception('文件不存在');
        }

        $jsonStr = fread(fopen($filePath, 'r'), filesize($filePath));
        $json = json_decode($jsonStr);

        $pattern = '/\d{4}/';
        $createYear = preg_match($pattern, $json->info->create_time, $matches) ? $matches[0] : date("Y");

        $_school = [
            'name' => $json->info->school,
            'province' => $json->info->sheng,
            'url' => count(array_filter(explode(',', $json->info->web))) > 0 ? array_filter(explode(',', $json->info->web))[0] : null,
            'type' => $json->info->mark3, // 院校类型/类型
            'level' => $json->info->mark2, // 办学层次
            'bxType' => $json->info->mark1, // 办学类型
            //'thumb' => $json->info->school,
            'logo' => $json->info->logo_local,
            'city' => $json->info->shuyu,
            'address' => $json->info->address1,
            'tel' => $json->info->tele,
            'email' => $json->info->email,
            'baoMingUrl' => $json->info->baoming,
            'chengJiUrl' => $json->info->chengji,
            'fenShuUrl' => $json->info->fenshu,
            'area' => $json->info->area,
            'jiaoYuTing' => $json->info->shuyu,
            'detail' => $json->info->detail,
            'createYear' => $createYear,
            'tags' => !empty($json->info->mark4) ? implode(',', $json->info->mark4) : null,
            // 'images' => !empty($json->imglist) ? implode(',', $json->imglist) : null,
        ];

        // 获取专业，去重
        $_school['spec'] = [];
        foreach ($json->info1 as $spec) {
            $_school['spec'][] = [
                'level1Name' => $spec->lei1,
                'level2Name' => $spec->lei2,
                'name' => $spec->lei3,
                'class' => $spec->zycc,
                // 'province' => $spec->sheng,
                'code' => $spec->zydm,
                'xz' => $spec->jbxz,
            ];
        }

        // 获取招生计划（等所有的专业入库完成，当前学校入库完成再入库绑定）
        $_school['plan'] = [];
        foreach ($json->zhaoshengjihua as $p) {
            $c = explode(',', $p->tiaojian);
            $_school['plan'][] = [
                'specName' => $p->name,
                'class' => $c[4],
                'year' => $c[0], // 年份
                'num' => $p->num,
                'whcd' => $c[3],
                'xz' => $p->years,
                'price' => is_numeric($p->price) ? $p->price : 0,
                'c1' => $c[2]
            ];
        }

        // 入库
        // 查同名、同省份
        try {
            DB::beginTransaction();
            $school = Qh_School::where('name', $_school['name'])->first();
            if ($school) {
                // 省份
                $province = is_array($school->province) ? $school->province : json_decode($school->province, JSON_UNESCAPED_UNICODE);
                $province = is_array($province) ? $province : (is_null($province) ? [] : [$province]);
                if (!in_array($_school['province'], $province)) {
                    $province[] = $_school['province'];
                    $school->province = json_encode($province, JSON_UNESCAPED_UNICODE);
                    $school->save();
                }
            }else {
                $_school['province'] = json_encode([$_school['province']], JSON_UNESCAPED_UNICODE);
                $school = Qh_School::create(Arr::except($_school, ['spec', 'plan']));

                // 创建专业
                $specIds = [];
                foreach ($_school['spec'] as $_spec) {
                    $provinces = is_array($school->province) ? json_encode($school->province, JSON_UNESCAPED_UNICODE) : $school->province;
                    // 一级专业
                    $spec1 = Qh_SchoolSpec::where('name', $_spec['level1Name'])->where('code', $_spec['code'])->where('level', 1)->first();
                    if (!$spec1) {
                        $spec1 = Qh_SchoolSpec::create([
                            'parentId' => null,
                            'level' => 1,
                            'name' => $_spec['level1Name'],
                            'class' => $_spec['class'],
                            'province' => $provinces,
                            'code' => $_spec['code'],
                            'xz' => $_spec['xz']
                        ]);
                    }

                    // 二级专业
                    $spec2 = Qh_SchoolSpec::where('name', $_spec['level2Name'])->where('code', $_spec['code'])->where('level', 2)->first();
                    if (!$spec2) {
                        $spec2 = Qh_SchoolSpec::create([
                            'parentId' => $spec1->id,
                            'level' => 2,
                            'name' => $_spec['level2Name'],
                            'class' => $_spec['class'],
                            'province' => $provinces,
                            'code' => $_spec['code'],
                            'xz' => $_spec['xz']
                        ]);
                    }

                    // 三级专业
                    $spec3 = Qh_SchoolSpec::where('name', $_spec['name'])->where('code', $_spec['code'])->where('level', 3)->first();
                    if (!$spec3) {
                        $spec3 = Qh_SchoolSpec::create([
                            'parentId' => $spec2->id,
                            'level' => 3,
                            'name' => $_spec['name'],
                            'class' => $_spec['class'],
                            'province' => $provinces,
                            'code' => $_spec['code'],
                            'xz' => $_spec['xz']
                        ]);
                    }

                    $specIds[] = $spec3->id;
                }

                // 将专业和学校关联
                $specIds = array_merge($specIds, $school->spec()->pluck('schoolSpecId')->toArray());
                $school->spec()->sync($specIds);

                // 创建招生计划
                foreach ($_school['plan'] as $_plan) {
                    $spec = Qh_SchoolSpec::where('name', $_plan['specName'])->where('level', 3)->first();

                    if ($spec) {
                        $_plan['schoolId'] = $school->id;
                        $_plan['schoolSpecId'] = $spec->id;
                        Qh_SchoolPlan::create(Arr::except($_plan, ['specName']));
                    }
                }
            }

            DB::commit();
        }catch (Exception $e) {
            DB::rollBack();
            throw new Exception($e->getMessage());
        }

        // 删除文件
        unlink($filePath);

        return $this->restful();
    }
}
